import { _decorator, Component, Node, Button, Input } from "cc";
const { ccclass, property } = _decorator;
// @ccclass("Utils")
export const Utils: Util = {
  addClickEvent(node, target, component, handler) {
    let eventHandler = new Component.EventHandler();
    eventHandler.target = target;
    eventHandler.component = component;
    eventHandler.handler = handler;
    let clickEvents = node.getComponent(Button).clickEvents;
    clickEvents.push(eventHandler);
  },

  addSlideEvent(node, target, component, handler) {
    let eventHandler = new cc.Component.EventHandler();
    eventHandler.target = target;
    eventHandler.component = component;
    eventHandler.handler = handler;

    let slideEvents = node.getComponent(cc.Slider).slideEvents;
    slideEvents.push(eventHandler);
  },
  addEscEvent(node: Node) {
    node.on(
      Input.EventType.KEY_DOWN,
      (e) => {
        switch (e.keyCode) {
          case cc.macro.KEY.back:
            break;
        }
      },
      this
    );
  },
  preload(url: string, cb = (...args) => {}) {
    return cc.director.preloadScene(url, cb);
  },
  setFitSreenMode(node: any) {
    if (!node) {
      node = cc.find("Canvas");
    }
    // let node = cc.find("Canvas");
    // let size = cc.view.getFrameSize();
    let size = cc.view.getFrameSize();
    let w = size.width;
    let h = size.height;
    let cvs = node.getComponent(cc.Canvas);
    let designResolution = cc.view.getDesignResolutionSize();
    let dw = designResolution.width;
    // let dw = cc.Canvas.instance.designResolution.width;
    let dh = designResolution.height;
    // let dh = cc.Canvas.instance.designResolution.height;
    //如果更宽 则让高显示满
    if (w / h > dw / dh) {
      cvs.fitHeight = true;
      cvs.fitWidth = false;
    } else {
      //如果更高，则让宽显示满
      cvs.fitHeight = false;
      cvs.fitWidth = true;
    }
  },
};

export interface Util {
  addClickEvent: (node, target, component, handler) => any;
  addSlideEvent: (node, target, component, handler) => any;
  addEscEvent: (node: Node) => any;
  preload: (url: string, cb: (...args) => any) => any;
  setFitSreenMode: (node?: Node | null) => any;
}
